package java6681.lesson10;

import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.*;
import java.util.Scanner;

/**
 * @author Junichiro
 * @description
 * @date 2021-05-16 16:42
 **/

public class TextFile6681Controller {
    static String errMsg = "";
    @FXML
    private Label lblSource;

    @FXML
    private Label lblTarget;

    @FXML
    private TextArea taText;

    @FXML
    void copyFile() {
        inputText(lblSource.getText());
        copy6681(lblSource.getText(),lblTarget.getText());
        try (FileInputStream fis = new FileInputStream(lblSource.getText())){
            byte[] bys = new byte[1024];
            int len = 0;
            while ((len = fis.read(bys)) != -1) {
                taText.setText(new String(bys,0,len));
                System.out.print(new String(bys,0,len));//千万要带上len的使用
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
    @FXML
    void selectSource(){
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("来源文件");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("All Images", "*.*"),
                new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                new FileChooser.ExtensionFilter("TXT", "*.txt")
        );
        fileChooser.setInitialDirectory(new File("."));
        File file = fileChooser.showOpenDialog(new Stage());
        if (file == null){
            return;
        }
        lblSource.setText(file.getAbsolutePath());
    }

    @FXML
    void selectTarget() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("复制到新文件");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("All Images", "*.*"),
                new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                new FileChooser.ExtensionFilter("TXT", "*.txt")
        );
        fileChooser.setInitialDirectory(new File("."));
        File file = fileChooser.showOpenDialog(new Stage());
        if (file == null){
            return;
        }
        lblTarget.setText(file.getAbsolutePath());
    }
    private static long copy6681(String sourceName, String targetName) {
        // 定义一个字节数组，作为缓冲区-->buff
        byte[] buff = new byte[1024];
        int len = 0;
        int size = 0;

        //针对源文件，创建带缓冲的输入流
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceName))) {
            //针对目标文件，创建带缓冲的输出流
            try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetName));) {
                //循环执行下列步骤，直到文件结束
                //1）从输入流中读取数据存入buff
                //2）再把buff中的内容写入到输出流
                //3）累加读到的字节数-->size
                while ((len = bis.read(buff)) != -1) {
                    bos.write(buff, 0, len);
                    size += len;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回字节数
        return size;
    }

    private static void inputText(String filename) {
        File target = new File(filename);
        // 如果输入包含目录, 判断上级目录是否存在, 不存在则创建, 创建失败则显示错误信息 (比如输入的盘符不存在的情况)
        File parent = target.getParentFile();
        if(parent != null && !parent.exists()){
            if(!parent.mkdirs()){
                errMsg = "指定目录无法创建 ";
            }
        }
        // 在外面声明Writer变量, 以便后面finally中来关闭它
        Writer writer = null;
        try {
            writer = new FileWriter(target);
            System.out.println("请逐行输入要写入文件的内容, 直到输入end结束");
            while (true) {
                // 循环输入文本, 向文件中写入, 输入一行写一行, 直到输入end时结束
                String input = new Scanner(System.in).nextLine();
                if ("end".equals(input.trim().toLowerCase())) {
                    break;
                }
                writer.write(input + "\r\n");
            }
        } catch (IOException e) {
            // 如果写入过程中出现错误, 则保存错误信息, 并且返回0
            errMsg = e.getMessage();
        } finally {
            // 最后如果writer的指向不为null, 就关闭它 (可能上面过程中给writer赋值时错误, 这时候还close就会报错)
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    errMsg = "字符流关闭失败";
                }
            }
        }
    }

}

